//
//  StartConditionController.m
//  YSSmartHome
//
//  Created by yanghao on 16/9/12.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "StartConditionController.h"
#import "AddConditionCell.h"
#import "LinkageDeviceSelectController.h"
#import "ZTLinkageInfo.h"
#import "DeviceConditionController.h"
#import "JXMovableCellTableView.h"
#import "MGSwipeTableCell.h"
#import "GlobalConst.h"
static NSString *const  kAddConditionCellIdentifier = @"kAddConditionCellIdentifier";
@interface StartConditionController ()
<
JXMovableCellTableViewDataSource,
JXMovableCellTableViewDelegate,
MGSwipeTableCellDelegate
>
@property(nonatomic, strong)JXMovableCellTableView *tableView;
@property(nonatomic, strong)UIView* bottomView;


@end

@implementation StartConditionController


#pragma mark - life cycle
- (void)dealloc
{
    debugLogInfo(@"StartConditionController delloc");
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubViews];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveLinkage:) name:kZTAddLinkageInfoNotifKey object:nil];
}

#pragma mark - event response
- (void)receiveLinkage:(NSNotification *)notif
{
    NSArray *linkages = notif.object;
    NSMutableArray *delArray = [NSMutableArray array];
    for (ZTLinkageInfo *link in linkages)
    {
        if (link.linkageType == ZTLinkageTypeCondition)
        {
            for (ZTLinkageInfo *tempLinkage in self.linkageInfos)
            {
                if (tempLinkage.linkItemDes.oprId == link.linkItemDes.oprId && tempLinkage.device == link.device)
                {
                    [delArray addObject:tempLinkage];
                }
            }
        }
    }
    [self.linkageInfos removeObjectsInArray:delArray];
    [self.linkageInfos addObjectsFromArray:linkages];
    [self.tableView reloadData];
}

- (void)didTappedSureButton:(UIButton *)sureButton
{
    if (self.startConditionBlock)
    {
        self.startConditionBlock(self.linkageInfos);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (0 == section)
    {
        return self.linkageInfos.count;
    }
    if (1 == section)
    {
        return 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1)
    {
        AddConditionCell *cell = [tableView dequeueReusableCellWithIdentifier:kAddConditionCellIdentifier];
        if (self.linkageType == ZTLinkageTypeAction)
        {
            cell.m_strAddBtnTitle = @"添加新动作";
        }
        else if(self.linkageType == ZTLinkageTypeCondition)
        {
            cell.m_strAddBtnTitle = @"添加新条件";
        }
        return cell;
    }
    else
    {
        MGSwipeTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell)
        {
            cell = [[MGSwipeTableCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.rightButtons = [self createRightButtons:2];
            cell.delegate = self;
        }
        NSString *channle = nil;
        ZTLinkageInfo *linkageInfo = self.linkageInfos[indexPath.row];
        if (linkageInfo.device.devType == ZTDeviceTypeOneWay0Switch ||
            linkageInfo.device.devType == ZTDeviceTypeOneWaySwitch ||
            linkageInfo.device.devType == ZTDeviceTypeTwoWay0Switch ||
            linkageInfo.device.devType == ZTDeviceTypeTwoWaySwitch ||
            linkageInfo.device.devType == ZTDeviceTypeThreeWay0Switch ||
            linkageInfo.device.devType == ZTDeviceTypeThreeWaySwitch ||
            linkageInfo.device.devType == ZTDeviceTypeFourWay0Switch ||
            linkageInfo.device.devType == ZTDeviceTypeFourWaySwitch ||
            linkageInfo.device.devType == ZTDeviceTypeOneWaySocket
            ) {
            switch (linkageInfo.linkItemDes.oprId)
            {
                case 0x01:
                    channle = @"一路";
                    break;
                case 0x02:
                    channle = @"二路";
                    break;
                case 0x03:
                    channle = @"三路";
                    break;
                case 0x04:
                    channle = @"四路";
                    break;
                default:
                    break;
            }
            cell.textLabel.text = [NSString stringWithFormat:@"%@  %@", [linkageInfo.device getDeviceName] , channle];
        }else {
            cell.textLabel.text = [NSString stringWithFormat:@"%@", [linkageInfo.device getDeviceName]];
        }
        if (linkageInfo.device == nil ) {
            cell.textLabel.text = @"时间信息";
        }
        switch (linkageInfo.linkItemDes.tlv.type) {
            case XAI_DATA_TYPE_BIN_BOOL:
            {
                uint8_t isOpen = 0;
                memcpy(&isOpen,  [linkageInfo.linkItemDes.tlv getPayloadbyte], sizeof(uint8_t));
                if (isOpen) {
                    cell.detailTextLabel.text = linkageInfo.strSelectDesc;
                }else
                {
                    cell.detailTextLabel.text = linkageInfo.strNormalDesc;
                }
                break;
            }
            default:
                break;
        }
        return cell;
    }
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ( 0 == indexPath.section)
    {
        DeviceConditionController *deviceConditionVc = [[DeviceConditionController alloc]init];
        deviceConditionVc.linkageType = self.linkageType;
        ZTLinkageInfo *linkageInfo =  self.linkageInfos[indexPath.row];
        deviceConditionVc.linkItemDes = linkageInfo.linkItemDes;
        [self.navigationController pushViewController:deviceConditionVc animated:YES];
    }
    //点击添加新动作或者新条件
    else if (1 == indexPath.section)
    {
        LinkageDeviceSelectController *conditionSelectVc  = [[LinkageDeviceSelectController alloc]init];
        conditionSelectVc.linkageType = self.linkageType;
        [self.navigationController pushViewController:conditionSelectVc animated:YES];
    }
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (0 == section) {
        if (self.linkageType == ZTLinkageTypeAction) {
            return @"已添加的动作(长按可调整动作的先后顺序)";
        }else if (self.linkageType == ZTLinkageTypeCondition) {
            return @"已添加的条件";
        }
    }
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (0 == section) {
        return 30;
    }
    return 0;
}
-  (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (0  == section) {
        return 0;
    }
    return 0;
}


#pragma mark - MGSwipeTableCellDelegate
-(BOOL) swipeTableCell:(MGSwipeTableCell*) cell tappedButtonAtIndex:(NSInteger) index direction:(MGSwipeDirection)direction fromExpansion:(BOOL) fromExpansion
{
    debugLogInfo(@"Delegate: button tapped, %@ position, index %d, from Expansion: %@",
          direction == MGSwipeDirectionLeftToRight ? @"left" : @"right", (int)index, fromExpansion ? @"YES" : @"NO");
    
    if (direction == MGSwipeDirectionRightToLeft && index == 0) {
        //delete button
        NSIndexPath * path = [_tableView indexPathForCell:cell];
        [_linkageInfos removeObjectAtIndex:path.row];
        [_tableView deleteRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationLeft];
//        if (self.linkageType == ZTLinkageTypeAction ) {
            if (self.startConditionBlock) {
                self.startConditionBlock(_linkageInfos);
            }
//        }
        return NO;
    }
    return YES;
}

#pragma mark - JXMovableCellTableViewDataSource
- (NSArray *)dataSourceArrayInTableView:(JXMovableCellTableView *)tableView
{
    return _linkageInfos.copy;
}

- (void)tableView:(JXMovableCellTableView *)tableView newDataSourceArrayAfterMove:(NSArray *)newDataSourceArray
{
    _linkageInfos = newDataSourceArray.mutableCopy;
}

#pragma mark - private method
- (void)initNavigationView
{
    if (self.linkageType == ZTLinkageTypeAction)
    {
        self.navigationItem.title = @"启动动作";
    }
    else if (self.linkageType == ZTLinkageTypeCondition)
    {
        self.navigationItem.title = @"启动条件";
    }
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(didTappedSureButton:)];
}

- (void)initSubViews
{
    [self initNavigationView];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.tableView];
    [self layoutPageSubViews];
}
- (void)layoutPageSubViews
{
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.leading.bottom.equalTo(self.view);
        make.height.equalTo(kIphoneSize_Height(67));
    }];
    [self.tableView makeConstraints:^(MASConstraintMaker *make) {
        make.top.trailing.leading.equalTo(self.view);
        make.bottom.equalTo(self.bottomView.top);
    }];
}
- (NSArray *)createRightButtons:(int)number
{
    NSMutableArray * result = [NSMutableArray array];
    UIColor * colors[2] = {RGBColor(239, 75, 58),
        RGBColor(204, 204, 204)};
    UIImage * icons[2] = {[UIImage imageNamed:@"scene_bigdel"], [UIImage imageNamed:@"scene_bigedit"]};
    for (int i = 0; i < number; ++i)
    {
        MGSwipeButton * button = [MGSwipeButton buttonWithTitle:@"" icon:icons[i] backgroundColor:colors[i] padding:15 callback:^BOOL(MGSwipeTableCell * sender){
            debugLogInfo(@"Convenience callback received (left).");
            return YES;
        }];
        [result addObject:button];
    }
    return result;
}

#pragma mark - getters and setters
- (NSMutableArray *)linkageInfos
{
    if (!_linkageInfos) {
        _linkageInfos = [NSMutableArray array];
    }
    return _linkageInfos;
}
- (JXMovableCellTableView *)tableView
{
    if (!_tableView) {
        _tableView = [[JXMovableCellTableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = kBgColor;
        _tableView.sectionHeaderHeight = 0;
        _tableView.sectionFooterHeight = 0;
        _tableView.rowHeight = 55;
        [_tableView registerClass:[AddConditionCell class] forCellReuseIdentifier:kAddConditionCellIdentifier];
    }
    return _tableView;
}

- (UIView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[UIView alloc]init];
        _bottomView.backgroundColor = kBgColor;
    }
    return _bottomView;
}
@end

